# coding:utf-8
"""
@author: jing
@contact: 529548204@qq.com
@file: serializer.py
@time: 2022/5/24 16:56
"""
from django.utils.translation import gettext_lazy
from .models import *
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


class UserSerializers(serializers.ModelSerializer):
    class Meta(object):
        model = User
        exclude = ['password',
                   'groups',
                   'user_permissions',
                   'is_superuser',
                   'last_login',
                   "is_staff",
                   "is_active",
                   ]
        extra_kwargs = {
            "usertype": {
                "required": True
            }
        }

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data.update(usertype=instance.get_usertype_display())
        # data.pop("password")
        return data

    # def create(self, validated_data):
    #     user = super().create(validated_data)
    #     user.set_password(validated_data['password'])
    #     user.save()


class GetLoginTokenSerializers(TokenObtainPairSerializer):

    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = super().get_token(self.user)
        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)
        data['username'] = self.user.username  # 这个是你的自定义返回的
        data['user_id'] = self.user.id  # 这个是你的自定义返回的
        return data
        # except Exception:
        #     return Exception
